package cn.ycc1.boot3kafka.controller;

import cn.ycc1.boot3kafka.entity.UserMessage;
import cn.ycc1.boot3kafka.service.KafkaProducerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @author ycc
 * @date 2025/11/16
 * Kafka 的设计哲学：
 * 1.所有消费者都必须属于一个消费者组
 * 2.这是 Kafka 消息分发机制的基础
 * 3.通过消费者组实现：
 *  负载均衡（同组内消费者分摊分区）
 *  消息顺序保证
 *  消费进度跟踪
 *
 *  # 发送简单消息
 * curl -X POST "http://localhost:8080/api/kafka/send?message=Hello Kafka"
 * # 发送带key的消息
 * curl -X POST "http://localhost:8080/api/kafka/send-with-key?key=user-1&message=User message"
 * # 发送用户消息
 * curl -X POST "http://localhost:8080/api/kafka/send-user" \
 *   -H "Content-Type: application/json" \
 *   -d '{"id":1,"name":"张三","email":"zhangsan@example.com"}'
 * # 批量发送
 * curl -X POST "http://localhost:8080/api/kafka/send-batch?count=5"
 */
@RequestMapping("/kafka")
@RestController
public class TestController {
    @Autowired
    private KafkaProducerService kafkaProducerService;

    @GetMapping("/test1")
    public String test1(){
        return "hello kafka";
    }

    /**
     * 发送简单消息
     */
    @PostMapping("/send")
    public String sendMessage(@RequestParam String message) {
        kafkaProducerService.sendMessage(message);
        return "消息已发送: " + message;
    }

    /**
     * 发送带key的消息
     */
    @PostMapping("/send-with-key")
    public String sendMessageWithKey(@RequestParam String key,
                                     @RequestParam String message) {
        kafkaProducerService.sendMessageWithKey(key, message);
        return "带key消息已发送";
    }

    /**
     * 发送用户消息
     */
    @PostMapping("/send-user")
    public String sendUserMessage(@RequestBody UserMessage userMessage) {
        kafkaProducerService.sendUserMessage(userMessage);
        return "用户消息已发送";
    }

    /**
     * 批量发送消息
     */
    @PostMapping("/send-batch")
    public String sendBatchMessages(@RequestParam int count) {
        for (int i = 1; i <= count; i++) {
            kafkaProducerService.sendMessage("测试消息 " + i);
        }
        return "已发送 " + count + " 条消息";
    }
}
